from django.core.mail import send_mail
from django.shortcuts import render
from django.conf import settings
# Create your views here.
from rest_framework.views import APIView
from rest_framework.response import Response
from django.contrib.auth.hashers import make_password
from .models import *
from .ser import Roleser,Userser
from itsdangerous import TimedJSONWebSignatureSerializer
import re
from .tasks import send_email_task
token_serializer = TimedJSONWebSignatureSerializer(settings.SECRET_KEY, 1800)

# send_mail
#注册
class RoleView(APIView):
    def post(self,request):
        #获取网页，提交数据
        name = request.data.get('name')
        #获取数据库内容，用来判断角色
        obj_role=Role.objects.filter(name=name)
        if obj_role:
            return Response({'msg':'角色存在','code':201})
        role_ser=Roleser(data=request.data)
        if role_ser:
            role_ser.is_valid()
            role_ser.save()
            return Response({'msg':'添加成功','code':200})
        else:
            return Response({'error':role_ser.errors})

class RegisterView(APIView):
    def post(self,request):
        username = request.data.get('username')
        password1 = request.data.get('password1')
        password2 = request.data.get('password2')
        phone = request.data.get('phone')
        email = request.data.get('email')
        role_id = request.data.get('role')

        if not all([username , password1 , password2 , phone , email , role_id]):
            return Response({'msg':'数据不完整','code':400})
        phone_re = re.compile(r'^1(3\d|4[4-9]|5[0-35-9]|6[67]|7[013-8]|8[0-9]|9[0-9])\d{8}$')
        if not re.search(phone_re, phone):
            return Response({'msg': '手机号不符合规范', 'code': 400})
        user_obj=User.objects.filter(username=username)

        if user_obj:
            return Response({'msg':'用户存在','code':202})

        if password1 == password2:
            user_data={
                'username': username,
                'password1': make_password(password1),
                'phone': phone,
                'email': email,
                'role': role_id,
            }
            user_ser=Userser(date=user_data)
            if user_ser.is_valid():
                user_ser.save()
                user_info = {'user_id' : user_ser.data.get('id')}
                token = token_serializer.dumps(user_info).decode()
                send_email_task.delay(username, token, email)

                return Response({'msg':'注册成功','code':200})
            else:
                return Response({'error': user_ser.errors})
        else:
            return Response({'msg': '两次密码不一致','code':400})


class ActiveView(APIView):
    def get(self,request):
        print(request.query_params.get('token'))
        return Response({'msg':'ok' , 'code':200})

